package com.ayf.payment.game.api.Template;

import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author: zh-liang
 * @Date : 2020-03-26 20:17
 */
@Component
public class TemplateUtils {
    @Autowired
    private TemplateEngine engine;

    /**
     * 导出html
     *
     * @param freeTempName
     * @param fileName
     * @param context
     * @param response
     */
    public void exportHTML(String freeTempName, String fileName, Context context, HttpServletResponse response) {
        OutputStream os = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(), StandardCharsets.UTF_8));
            byte[] bytes = engine.process(freeTempName, context).getBytes(StandardCharsets.UTF_8);
            os = response.getOutputStream();
            // 将字节流传入到响应流里,响应到浏览器
            os.write(bytes);
            os.close();
        } catch (Exception ex) {
            throw new RuntimeException("导出失败");
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException ioEx) {
                LogPortal.error("导出失败:", ioEx);
            }
        }
    }
}
